/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
package example.springboot.service;

import example.springboot.dto.WordDTO;
import example.springboot.entity.FavoriteWord;
import example.springboot.entity.Word;
import example.springboot.mapper.FavoriteWordMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FavoriteWordService {

    @Autowired
    private FavoriteWordMapper favoriteWordMapper;

    /**
     * 添加收藏
     */
    public boolean addFavorite(Integer userId, Integer wordId) {
        // 检查是否已收藏
        FavoriteWord exist = favoriteWordMapper.findByUserIdAndWordId(userId, wordId);
        if (exist != null) {
            throw new RuntimeException("该单词已在生词本中");
        }

        // 添加收藏
        FavoriteWord favoriteWord = new FavoriteWord();
        favoriteWord.setUserId(userId);
        favoriteWord.setWordId(wordId);
        
        return favoriteWordMapper.insert(favoriteWord) > 0;
    }

   
    public boolean removeFavorite(Integer userId, Integer favoriteId) {
       
        return favoriteWordMapper.deleteById(favoriteId) > 0;
    }

    /**
     * 根据用户ID和单词ID删除收藏
     */
    public boolean removeFavoriteByWordId(Integer userId, Integer wordId) {
        return favoriteWordMapper.deleteByUserIdAndWordId(userId, wordId) > 0;
    }

    /**
     * 获取用户的收藏单词列表
     */
    public List<WordDTO> getFavoriteWords(Integer userId) {
        List<Word> words = favoriteWordMapper.findFavoriteWordsByUserId(userId);
        
        // 转换为DTO
        return words.stream().map(word -> {
            WordDTO dto = new WordDTO();
            BeanUtils.copyProperties(word, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 统计用户收藏数量
     */
    public int countFavoriteWords(Integer userId) {
        return favoriteWordMapper.countByUserId(userId);
    }

    /**
     * 检查单词是否已收藏
     */
    public boolean isFavorite(Integer userId, Integer wordId) {
        FavoriteWord favoriteWord = favoriteWordMapper.findByUserIdAndWordId(userId, wordId);
        return favoriteWord != null;
    }
}

